package com.janwen.spring.trx.transactional;

import javax.sql.DataSource;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.janwen.spring.trx.declarative.Foo;

/**
 * 类上添加Transactional,以方法的Transactional配置为标准
 * @author janwen
 * Aug 28, 2012
 */
//@Transactional
public class TrxServcieImpl implements TrxService {

	
	static final Log logger = LogFactory.getLog(TrxServcieImpl.class);
	@Override
	public Foo getFoo(String fooName) {
		logger.info("getFoo Transactional");
		return null;
	}
	
	@Override
	public Foo getFoo(String fooName, String barName) {
		
		return null;
	}
	private DataSource dataSource;
	public DataSource getDataSource() {
		return dataSource;
	}

	public void setDataSource(DataSource dataSource) {
		this.dataSource = dataSource;
	}

	@Override
	@Transactional(readOnly=false,propagation=Propagation.REQUIRED)
	public void insertFoo(Foo foo) {
		String sql = "insert into stuff set name=?,age=?";
		JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
		jdbcTemplate.update(sql, foo.getName(),foo.getAge());
		//updateFoo(foo);

	}

	@Override
	@Transactional(readOnly=false,propagation=Propagation.REQUIRED)
	public void updateFoo(Foo foo) {
		logger.info("updateFoo transactional");
		String sql = "update stuff set age=?,name=? where name=?";
		JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
		jdbcTemplate.update(sql,foo.getAge()+2,foo.getName()+"_new_",foo.getName());
		throw new RuntimeException("updateFoo exception");
	}

	@Override
	public void createFoo(Foo foo) {
		//insertFoo方法中的事务失效,createFoo方法必须带有@Transactional Annotation事务生效
		insertFoo(foo);
		
	}
	
	

}
